<template>
  <div>
    <div style="padding: 50px 0">
      <van-field
        v-model="message"
        rows="5"
        autosize
        label=""
        type="textarea"
        class="border-b-1"
        placeholder="请输入您的意见"
      />
      <div @click="addOpnion" class="addOp">
        <i class="iconfont icon-add color-9 font14 mr5"></i>
        <span class="font14 color-3">常用意见</span>
      </div>
      <van-popup v-model="opnionPicker" position="bottom">
        <van-picker
          show-toolbar
          :columns="opnionList"
          @confirm="opnionConfirm"
          @cancel="opnionPicker = false"
        />
      </van-popup>

      <van-popup v-model="groupSinglePicker" position="bottom">
        <van-picker
          show-toolbar
          :columns="groups"
          value-key="description"
          @confirm="singleConfirm"
          @cancel="groupSinglePicker = false"
        />
      </van-popup>

      <van-popup v-model="groupPicker" position="bottom">
        <div>
          <div class="btn">
            <div @click="groupPicker = false" class="cancle">取消</div>
            <div @click="onGroupConfirm" class="confirm">确定</div>
          </div>
          <van-checkbox-group v-model="groupChecked">
            <van-cell-group>
              <van-cell
                v-for="(item, index) in groups"
                clickable
                :key="index"
                :title="item.description"
                @click="toggle(item, index)"
              >
                <template #right-icon>
                  <van-checkbox :name="item.id" ref="checkboxes" />
                </template>
              </van-cell>
            </van-cell-group>
          </van-checkbox-group>
        </div>
      </van-popup>

      <div class="bge"></div>

      <!-- 选择抄送人员 -->
      <div v-if="hasCopy" class="copyDiv" @click="toSelectCopy">
        <div class="color-8 font12">选择抄送人员：</div>
        <div style="margin-top: 5px" class="color-8 font13">
          <span v-for="(item, index) in copyList" :key="item.id">
            <span class="font13 color-8" v-if="index == 0">{{
              item.name
            }}</span>
            <span class="font13 color-8" v-else>,{{ item.name }}</span>
          </span>
        </div>
      </div>

      <div class="bge"></div>
      <div class="decisionList">
        <van-radio-group v-model="decisionRadio" @change="decisionChange">
          <van-radio
            v-for="item in decisions"
            :key="item.id"
            :name="item.id"
            class="font14 ht40"
          >
            {{ item.description }}
            <div
              v-if="decisionRadio == item.id && !selectData"
              class="color-9 font14"
            >
              {{ uListName }}
            </div>
            <div
              v-if="decisionRadio == item.id && selectData"
              class="color-9 font14"
            >
              <div v-if="selectData.length > 0" class="color-9 font14">
                <span v-for="(item2, index2) in selectData" :key="item2.id">
                  <span v-if="index2 == 0">{{ item2.description }}</span>
                  <span v-else>,{{ item2.description }}</span>
                </span>
              </div>
              <span v-else>{{ selectData.description }}</span>
            </div>
            <div
              v-if="decisionRadio == item.id && decision == 'end'"
              class="color-9 font14"
            >
              当前决策项无需候选人
            </div>
          </van-radio>
        </van-radio-group>
      </div>
      <div class="pof-btn">
        <van-button
          @click="submitClick"
          :loading="isSubmit"
          loading-text="提交中"
          block
          class="bg-theme color-f ht46 font17"
          >提交</van-button
        >
      </div>
    </div>
  </div>
</template>
<script>
import { Notify, Toast } from "vant";
import {
  getDecisions,
  getOrgAndUser,
  getNextGroup,
  getVCOpinion,
  vcApproval,
} from "@/api/newtodo";
import { mapGetters } from "vuex";
export default {
  computed: {
    ...mapGetters(["user"]),
  },
  data() {
    return {
      message: "", // 意见
      opnionPicker: false,
      opnionList: ["同意", "不同意", "请审批", "请修改", "已阅"],
      params: {}, // 上个页面传过来的数据
      decisions: [], // 决策项
      decisionRadio: "",
      isSubmit: false, // 按钮是否处于提交状态
      isMore: false, // 是否多选
      uList: [], // 人
      uListName: "",
      copyDecision: {}, // 抄送决策项---》是指决策项的类型是否为抄送决策项
      hasCopy: false, // 当前选中的决策项是否含有抄送
      copyList: [], // 抄送所选的人
      selectData: null, // 已经在选人页面选过的人或者组织
      decision: "",
      groups: [],
      groupId: "",
      groupChecked: [],
      groupMultiSelect: "",
      groupPicker: false,
      groupSinglePicker: false,
      persopnMultiSelect: "",
    };
  },
  watch: {
    $route: {
      handler: function (val, oldVal) {
        if (!val.params.title && oldVal) {
          this.params = oldVal.params;
        } else {
          this.params = val.params;
        }
      },
      // 深度观察监听
      deep: true,
      immediate: true,
    },
  },
  activated() {
    // 缓存
    this.initData();
    if (
      localStorage.getItem("searchKeyword") != "{}" &&
      !!localStorage.getItem("searchKeyword")
    ) {
      if (this.params.isCopy == "false") {
        this.selectData = JSON.parse(localStorage.getItem("searchKeyword"));
      } else if (this.params.isCopy == "true") {
        this.copyList = JSON.parse(localStorage.getItem("searchKeyword"));
        this.selectData = this.params.selectPeople;
      }
      this.decisionRadio = this.params.currentDecision;
      localStorage.setItem("searchKeyword", "{}");
    }
    
    this.getDecisions();
  },

  methods: {
    initData() {
      this.message = ""; // 意见
      this.opnionPicker = false;
      this.decisions = []; // 决策项
      this.decisionRadio = "";
      this.isSubmit = false; // 按钮是否处于提交状态
      this.isMore = false; // 是否多选
      this.uList = []; // 人
      this.uListName = "";
      this.copyDecision = {}; // 抄送决策项---》是指决策项的类型是否为抄送决策项
      this.hasCopy = false; // 当前选中的决策项是否含有抄送
      this.copyList = []; // 抄送所选的人
      this.selectData = null; // 已经在选人页面选过的人或者组织
      this.decision = "";
      this.groups = [];
      this.groupId = "";
      this.groupChecked = [];
      this.groupMultiSelect = "";
      this.groupPicker = false;
      this.groupSinglePicker = false;
      this.persopnMultiSelect = "";
    },

    goBack() {
      this.$router.back(-1); //返回上一页
    },

    // 获取决策项
    getDecisions() {
      Toast.loading({
        message: "加载中...",
        forbidClick: true,
      });
      getDecisions(
        Object.assign(this.params, { userName: this.user.userName })
      ).then((res) => {
         Toast.clear();
        this.decisions = [];
        if (res.data && res.data.steps) {
          if (res.data.steps.nextstep) {
            this.decisions.push(res.data.steps.nextstep);
          } else {
            this.decisions = res.data.steps;
          }
        }
      })
      .catch((e)=>{
          Toast.clear();
      });
    },
    // 添加常用意见
    addOpnion() {
      this.opnionPicker = true;
    },
    opnionConfirm(value) {
      this.message = value;
      this.opnionPicker = false;
    },
    singleConfirm(value, index) {
      this.groupSinglePicker = false;
      this.groupId = value.id;
      this.getOrgAndUser(
        Object.assign(this.params, {
          nextStep: this.decisionRadio,
          persopnMultiSelect: this.persopnMultiSelect,
          nextGroup: this.groupId,
          userName: this.user.userName,
        })
      );
    },
    onGroupConfirm(value) {
      if (this.groupChecked.length == 0) {
        Toast({
          message: "请先选择组别",
          duration: 1500,
          icon: "success",
        });
        return;
      } else {
        this.groupPicker = false;
        for (var i in this.groupChecked) {
          if (i != 0) {
            this.groupId = this.groupId + ",";
          }
          this.groupId = this.groupId + this.groupChecked[i];
        }
        this.getOrgAndUser(
          Object.assign(this.params, {
            nextStep: this.decisionRadio,
            persopnMultiSelect: this.persopnMultiSelect,
            nextGroup: this.groupId,
            uerName: this.user.userName,
          })
        );
      }
    },
    toggle(item, index) {
      this.$refs.checkboxes[index].toggle();
    },
    // 决策项改变
    decisionChange(name) {
      for (var i in this.decisions) {
        if (this.decisions[i].id == name) {
          this.decisionRadio = name;
          getNextGroup(
            Object.assign(this.params, {
              nextStep: name,
              userName: this.user.userName,
            })
          ).then((res) => {
            this.groups = [];

            if (!Array.isArray(res.data.groups.group)) {
              this.groups.push(res.data.groups.group);
            } else {
              this.groups = res.data.groups.group;
            }
           
            this.groupMultiSelect = res.data.groups.multiSelect;
            if (this.groups.length == 0) {
              Toast({
                message: "无候选人员",
                duration: 1500,
                icon: "success",
              });
            } else {
              if (this.groups.length == 1) {
                this.groupId = this.groups[0].id;
                this.getOrgAndUser(
                  Object.assign(this.params, {
                    nextStep: name,
                    nextGroup: this.groupId,
                    userName: this.user.userName,
                  })
                );
              } else {
                if (this.groupMultiSelect == "1") {
                  this.groupPicker = true;
                } else {
                  this.groupSinglePicker = true;
                }
              }
            }
          });
        }
      }
    },
    // 根据所选决策项选择部门或者人（在本页面调取选人接口：如果只有一个人默认展示，否则跳页面选择人）
    getOrgAndUser(appDecision) {
      Toast.loading({
        message: "加载中...",
        forbidClick: true,
      });
      getOrgAndUser(appDecision).then((res) => {
        this.uList = [];

        if (!Array.isArray(res.data.persons.person)) {
          this.uList.push(res.data.persons.person);
        } else {
          this.uList = res.data.persons.person;
        }
        this.persopnMultiSelect = res.data.persons.multiSelect;

        getVCOpinion(appDecision).then((res) => {
          this.message = res.data.opinion.value;
          Toast.clear();
          if (this.uList.length == 0) {
            Notify({
              type: "warning",
              message: "当前决策项下无数据，请选择其他决策项",
              duration: 1300,
            });
          } else {
            if (this.uList.length == 1) {
              this.uListName = this.uList[0].name;
              this.selectData = this.uList[0];
            } else {
              //跳页面选人
              this.$router.push({
                name: "getOrgAndUser",
                params: Object.assign(
                  {
                    currentDecision: this.decisionRadio,
                    persopnMultiSelect: this.persopnMultiSelect,
                    isCopy: "false",
                    uList: this.uList,
                  },
                  this.params
                ),
              });
            }
          }
        });
      });
    },

    // 选择抄送人员
    toSelectCopy() {
      if (this.params.type) {
        // 待办流程的下一步
        getOrgAndUser({
          applyType: this.params.applyType,
          location: this.params.location,
          processInstId: this.params.processInstId,
          appDecision: this.copyDecision,
        }).then((res) => {
          if (res.data && res.data.length > 0) {
            if (res.data[0].user && res.data[0].user.length > 0) {
              var resUser = res.data[0].user;
              var uList = []; // 人
              var oList = []; // 组织
              var ouObj = {}; // 组织对象
              for (var i in resUser) {
                if (resUser[i].treeType == "user") {
                  uList.push(resUser[i]);
                }
                if (resUser[i].treeType == "org") {
                  oList.push(resUser[i]);
                  ouObj[resUser[i].id] = resUser[i];
                }
              }
              if (uList.length == 1) {
                this.copyList = uList;
              } else {
                // 跳页面选人
                this.$router.push({
                  name: "getOrgAndUser",
                  params: {
                    applyType: this.params.applyType,
                    location: this.params.location,
                    processInstId: this.params.processInstId,
                    processDefName: this.params.processDefName,
                    workItemId: this.params.workItemId,
                    type: this.params.type,
                    appDecision: this.copyDecision,
                    oldAppDecision: this.params.appDecision,
                    currentDecision: this.decisionRadio,
                    formData: this.params.formData,
                    isCopy: "true",
                    selectPeople: this.selectData,
                    allParams: this.params,
                  },
                });
              }
            } else {
              Notify({
                type: "warning",
                message: "抱歉，暂无抄送人员可供选择",
                duration: 1300,
              });
            }
          }
        });
      } else {
        // 起草下一步
        getOrgAndUser({
          applyType: this.params.applyType,
          location: this.params.location,
          appDecision: this.copyDecision,
        }).then((res) => {
          if (res.data && res.data.length > 0) {
            if (res.data[0].user && res.data[0].user.length > 0) {
              var resUser = res.data[0].user;
              var uList = []; // 人
              var oList = []; // 组织
              var ouObj = {}; // 组织对象
              for (var i in resUser) {
                if (resUser[i].treeType == "user") {
                  uList.push(resUser[i]);
                }
                if (resUser[i].treeType == "org") {
                  oList.push(resUser[i]);
                  ouObj[resUser[i].id] = resUser[i];
                }
              }
              if (uList.length == 1) {
                this.copyList = uList;
              } else {
                // 跳页面选人
                this.$router.push({
                  name: "getOrgAndUser",
                  params: {
                    applyType: this.params.applyType,
                    location: this.params.location,
                    appDecision: this.copyDecision,
                    oldAppDecision: this.params.appDecision,
                    currentDecision: this.decisionRadio,
                    formData: this.params.formData,
                    isCopy: "true",
                    selectPeople: this.selectData,
                  },
                });
              }
            } else {
              Notify({
                type: "warning",
                message: "抱歉，暂无抄送人员可供选择",
                duration: 1300,
              });
            }
          }
        });
      }
    },

    // 提交
    submitClick(e) {
      if (this.message == "") {
        Notify({ type: "warning", message: "请填写审批意见", duration: 1300 });
      } else if (!this.selectData) {
        Notify({
          type: "warning",
          message: "请选择办理人员或部门",
          duration: 1300,
        });
      } else {
        this.goNext();
      }
    },

    goNext() {
      let nextPerson = "";
      if (this.selectData.length > 0) {
        for (var i in this.selectData) {
          if (i != 0) {
            nextPerson = nextPerson + ",";
          }
          nextPerson = nextPerson + this.selectData[i].id;
        }
      } else {
        nextPerson = this.selectData.id;
      }
      
      vcApproval(
        Object.assign(this.params, {
          nextPerson: nextPerson,
          opinion: this.message,
          userName: this.user.userName,
        })
      )
        .then((res) => {
          this.isSubmit = false;
          this.moaBridge_ha_djfupt.refreshMOA();
          if (this.$route.params.fromMoa) {
            this.moaBridge_ha_djfupt.closeDoc({
              refresh: true,
              appcode: "djfupt",
            });
          } else {
            this.$router.replace({ path: "/newtodo" });
            localStorage.setItem("history", "");
          }
        })
        .catch((error) => {
          this.isSubmit = false;
          Notify({ type: "warning", message: "提交失败,请稍后重试" });
        });
    },
  },
};
</script>
<style scoped>
.border-b-1 {
  border-bottom: 1px solid #eee;
}
.ht40 {
  width: 100%;
  height: 50px;
  line-height: 50px;
  padding-left: 16px;
  border-bottom: 1px solid #eee;
}
.addOp {
  width: 100%;
  height: 40px;
  line-height: 40px;
  padding-left: 16px;
  font-size: unset;
  vertical-align: middle;
  display: table-cell;
}
.bge {
  width: 100%;
  height: 8px;
  background: #eee;
}
.decisionList {
  width: 100%;
}
.ht46 {
  height: 46px;
  line-height: 46px;
}
.pof-btn {
  position: fixed;
  right: 0;
  bottom: 0;
  left: 0;
}
.btn {
  display: flex;
  justify-content: space-between;
}
.cancle {
  padding: 15px 0px 15px 18px;
  font-size: 18px;
}
.confirm {
  padding: 15px 18px 15px 0px;
  font-size: 18px;
}

.copyDiv {
  width: 100%;
  padding: 16px;
}
</style>
